package com.imaker.frame.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log

/**
 * Created by Lvlufei on 2021/4/20
 *
 * @descr 广播-辅助工具
 */
object BroadcastUtils {
    private const val TAG = "BroadcastUtils"

    /**
     * 发送广播
     *
     * @param context
     * @param action
     * @param extras
     */
    fun sendBroadcast(context: Context?, action: String, extras: Bundle?) {
        if (context == null) {
            return
        }
        val intent = Intent(action)
        // 突破限制，实现所有应用都可以收到广播
        intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
        if (extras != null) {
            intent.putExtras(extras)
        }
        Log.i(TAG, "sendBroadcast: act [$action], extra: $extras")
        context.sendBroadcast(intent)
    }

    /**
     * 注册广播
     *
     * @param context
     * @param receiver
     * @param actions
     */
    fun registerReceiver(context: Context?, receiver: BroadcastReceiver?, vararg actions: String) {
        if (context == null || actions.size == 0 || receiver == null) {
            return
        }
        val filter = IntentFilter()
        for (i in actions.indices) {
            filter.addAction(actions[i])
            Log.i(TAG, "CarSpeed action = " + actions[i])
        }
        context.registerReceiver(receiver, filter)
    }

    /**
     * 注销广播
     *
     * @param context
     * @param receiver
     */
    fun unregisterReceiver(context: Context?, receiver: BroadcastReceiver?) {
        if (context == null || receiver == null) {
            return
        }
        try {
            context.unregisterReceiver(receiver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}